const WebSocket = require('ws');
const express = require('express');
const mysql = require('mysql');
const pool=require('../db/db')
const app = express();
const rooms=require('../model/rooms')
const user=require('../model/user')
const roomusers=require('../model/roomuser')
const message=require('../model/message')
const  SERVER_PORT=require('../config')

const wss = new WebSocket.Server({ port:3001 });
const clientsMap = new Map();
// const clientMap = new Map();
wss.on('connection', function connection(ws) {

    // console.log(clientsMap)
    // 获取客户端发送的房间ID和客户名
    ws.on('message', async function incoming(message) {
        ws.send('连接成功')
        console.log(clientsMap)
        const data = JSON.parse(message);
        console.log(data)
        const roomName = data.roomname;
        const msg=data.message;
        const cliendname=data.name;
        // 在数据库中查找房间


        // 在数据库中查找客户

        let clientId = await roomusers.findAll({
            attributes:['name'],
            where: {
                roomname: roomName,
                online:1}
        }
        );

// 提取用户名的数组
        const usernames = clientId.map(client => client.dataValues.name);
         // console.log(usernames)

        wss.clients.forEach(function (client) {
            if (client.readyState === WebSocket.OPEN&&client !== ws) {
                console.log(client)
                client.send(JSON.stringify(msg));
            }
        });


    })

});
module.exports=wss;

// 创建HTTP服务器


// 在数据库中查找或创建房间

